package com.gitee.linmt.converter;

import com.gitee.linmt.base.BaseDictionaryEnum;
import com.gitee.linmt.cache.DictionaryEnumCache;

import javax.persistence.AttributeConverter;

/**
 * @author lin-mt
 * @version 1.0.0
 * @since 1.0.0
 */
public class DictionaryEnumConverter<E extends BaseDictionaryEnum> implements AttributeConverter<E, String> {

    private final DictionaryEnumCache dictionaryEnumCache;

    public DictionaryEnumConverter(DictionaryEnumCache dictionaryEnumCache) {
        this.dictionaryEnumCache = dictionaryEnumCache;
    }

    @Override
    public String convertToDatabaseColumn(E baseDictionaryEnum) {
        return baseDictionaryEnum.getCode();
    }

    @Override
    public E convertToEntityAttribute(String code) {
        //noinspection unchecked
        return (E) dictionaryEnumCache.getByCode(code);
    }
}
